#!/bin/sh
# create -v3 logs and json's from DWG or DXF with dwgread -Ojson
srcdir="@srcdir@"
top_builddir="@top_builddir@"
CFLAGS="@CFLAGS@"
timeout="@TIMEOUT_30@"

case "$CFLAGS" in
    *-DDEBUG_CLASSES*) timeout="" ;;
    *) ;;
esac
make -s -C src
make -s -C programs dwgread
@DSYMUTIL@ programs/dwgread
v=-v3
# dummy to please shellcheck
test -z "$v" && echo $top_builddir
out=
ob="$b"
ext=

for d in "$@"; do
    case $d in
        -v*) v="$d"
             ;;
        *)
        if [ ! -f "$d" ]; then
            if [ -f "$srcdir/test/test-data/$d" ]
            then
                d="$srcdir/test/test-data/$d";
            elif [ -f "$srcdir/test/test-data/$d.dwg" ]
            then
                d="$srcdir/test/test-data/$d.dwg"
                ext=dwg
            elif [ -f "$srcdir/test/test-data/$d.dxf" ]
            then
                d="$srcdir/test/test-data/$d.dxf"
                ext=dxf
            fi
        fi
        xd=$(dirname "$d")
        dir=_$(basename "$xd")
        if [ "$dir" = "_test-data" ]; then dir=""; fi
        if [ "$dir" = "_td" ]; then dir=""; fi
        if [ "$dir" = "_." ]; then dir=""; fi
        if [ -z "$ext" ]; then
            case $(basename "$d") in
                *.dwg)  ext=dwg ;;
                *.DWG)  ext=dwg ;;
                *.dxf)  ext=dxf ;;
                *.DXF)  ext=dxf ;;
                *.json) ext=json ;;
                *.JSON) ext=json ;;
                *)      echo "Illegal extension for $d"; exit ;;
            esac
        fi
        b=$(basename "$d" .$ext)
        log="$b$dir.log"
        out="$b$dir.json"
        echo "$timeout @LTEXEC@ programs/dwgread $v -Ojson -o $out $d 2>$log"
        $timeout @LTEXEC@ programs/dwgread "$v" -Ojson -o "$out" "$d" 2>"$log"
        tail -n2 "$log"
        ;;
    esac
done
v=
b=$ob
